package com.ibm.iisp.common.util;

import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.commons.lang3.time.DateUtils;

/**
 * @author yangyz
 *
 */
public class DateUtilsExt extends DateUtils {
	/**
	 * @param cal
	 *            cal.
	 */
	public static void goMonthEnd(Calendar cal) {
		int oldMonth = cal.get(Calendar.MONTH);
		do {
			cal.add(Calendar.DATE, 1);
		} while (oldMonth == cal.get(Calendar.MONTH));

		cal.add(Calendar.DATE, -1);
	}

	/**
	 * @param cal
	 *            cal.
	 */
	public static void goNextMonthBegin(Calendar cal) {
		int oldMonth = cal.get(Calendar.MONTH);
		do {
			cal.add(Calendar.DATE, 1);
		} while (oldMonth == cal.get(Calendar.MONTH));

		// cal.add(Calendar.DATE, -1);
	}

	/**
	 * 转到离当前日期最后一个月底，如当前日期05-16,那么last month end就是04-30
	 *
	 * @param cal
	 *            cal.
	 */
	public static void goLastMonthEnd(Calendar cal) {
		int mnth = cal.get(Calendar.MONTH);
		cal.add(Calendar.DATE, 1);
		if (mnth == cal.get(Calendar.MONTH)) {
			// 给定日期不是月末
			while (mnth == cal.get(Calendar.MONTH)) {
				cal.add(Calendar.DATE, -1);
			}
			// cal.add(Calendar.DATE, -1);
		} else {
			// 给定日期是月末
			//cal.add(Calendar.MONTH, -1);
			cal.add(Calendar.DATE, -1);

		}
	}

	/**
	 * @param date
	 *            date.
	 * @return string.
	 */
	public static final String toGMT(Date date) {
		Locale aLocale = Locale.US;
		DateFormat fmt = new SimpleDateFormat("EEE,d MMM yyyy hh:mm:ss z", new DateFormatSymbols(aLocale));
		fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
		return fmt.format(date);
	}

	// /**
	// * @param reportDateString
	// * reportDate string.
	// * @return date object.
	// */
	// public static Date toReportDate(String reportDateString) {
	// try {
	// DateFormat fmt = new SimpleDateFormat("yyyyMMdd");
	// if (reportDateString.length() == 6) {
	// reportDateString += "01";
	// Date dt = fmt.parse(reportDateString);
	// Calendar cal = Calendar.getInstance();
	// cal.setTime(dt);
	// goMonthEnd(cal);
	// return cal.getTime();
	// }
	// return fmt.parse(reportDateString);
	// } catch (ParseException e) {
	// throw new RuntimeException(reportDateString +
	// " is not well formed. Sample form: '20130331'", e);
	// }
	// }

	/**
	 * @param cal
	 *            cal.
	 * @return boolean.
	 */
	public static boolean isMonthEnd(Calendar cal) {
		boolean flag = false;
		int mnth = cal.get(Calendar.MONTH);
		cal.add(Calendar.DATE, 1);
		if (mnth != cal.get(Calendar.MONTH)) {
			flag = true;
		}
		cal.add(Calendar.DATE, -1);
		return flag;
	}
}
